package com.woniuxy.demo.server.impl;

import com.woniuxy.examentity.ExamScoreResult;
import com.woniuxy.examentity.ExamSubmission;
import com.woniuxy.examentity.Question;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Auther: 刘博文  <br/>
 * Date: 2025/9/20:11:43  <br/>
 * Description:
 */
@Service
public class AIScoringService {

    @Autowired
    private ChatClient chatClient;

    // 模拟AI评分逻辑
    public ExamScoreResult scoreExam(ExamSubmission submission) {
        ExamScoreResult result = new ExamScoreResult();
        Map<String, Double> scores = new HashMap<>();
        Map<String, String> comments = new HashMap<>();

        double totalScore = 0.0;

        // 遍历所有题目进行评分
        for (Question question : submission.getExam().getQuestions()) {
            double score = 0.0;
            String comment = "";

            switch (question.getType()) {
                case "choice":
                    // 选择题评分（满分10分）
                    score = scoreChoiceQuestion(question,
                            submission.getAnswers().get(question.getId()));
                    comment = score >= 10 ? "回答正确！" : "回答错误，正确答案是选项" +
                            ((List<String>) question.getOptions()).get((Integer) question.getAnswer());
                    break;

                case "essay":
                    // 简答题评分（满分15分）
                    score = scoreEssayQuestion(question,
                            (String) submission.getAnswers().get(question.getId()));
                    comment = generateEssayCommentByAI(question,
                            (String) submission.getAnswers().get(question.getId()));
                    break;

                case "programming":
                    // 编程题评分（满分20分）
                    score = scoreProgrammingQuestion(question,
                            (String) submission.getAnswers().get(question.getId()));
                    comment = generateProgrammingCommentByAI(question,
                            (String) submission.getAnswers().get(question.getId()));
                    break;
            }

            scores.put(question.getId(), score);
            comments.put(question.getId(), comment);
            totalScore += score;
        }

        result.setTotalScore(totalScore);
        result.setScores(scores);
        result.setComments(comments);

        return result;
    }

    // 选择题评分逻辑
    private double scoreChoiceQuestion(Question question, Object userAnswer) {
        if (userAnswer == null) return 0.0;

        // 比较用户答案和正确答案
        if (userAnswer.equals(question.getAnswer())) {
            return 10.0; // 满分
        }
        return 0.0;
    }

    // 简答题评分逻辑（模拟AI评分）
    private double scoreEssayQuestion(Question question, String userAnswer) {
        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return 0.0;
        }

        // 简单的关键词匹配评分（实际应用中应该使用AI模型）
        String correctAnswer = (String) question.getAnswer();
        int matchCount = 0;
        String[] keywords = correctAnswer.split("[,，\\s]+");

        for (String keyword : keywords) {
            if (userAnswer.contains(keyword)) {
                matchCount++;
            }
        }

        // 根据匹配度计算得分
        double score = (double) matchCount / keywords.length * 15;
        return Math.round(score * 10) / 10.0; // 保留一位小数
    }

    // 编程题评分逻辑（模拟AI评分）
    private double scoreProgrammingQuestion(Question question, String userAnswer) {
        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return 0.0;
        }

        // 简单的评分逻辑（实际应用中应该运行代码测试）
        // 这里根据代码长度和关键词进行评分
        int lines = userAnswer.split("\n").length;
        double score = Math.min(lines, 20); // 最多20分

        // 检查关键代码结构
        if (userAnswer.contains("public") && userAnswer.contains("class")) {
            score += 2;
        }
        if (userAnswer.contains("main")) {
            score += 3;
        }

        return Math.min(score, 20.0); // 最高20分
    }

    // 使用AI生成简答题评语
    private String generateEssayCommentByAI(Question question, String userAnswer) {
        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return "未提供答案，无法评分。";
        }

        String correctAnswer = (String) question.getAnswer();

        String prompt = String.format(
                "你是一个Java编程考试的阅卷老师。请根据以下信息生成评语：\n" +
                        "题目：%s\n" +
                        "标准答案：%s\n" +
                        "学生答案：%s\n" +
                        "请结合标准答案和学生答案，给出200字左右的详细评语，指出回答的优缺点和改进建议。",
                question.getQuestion(), correctAnswer, userAnswer
        );

        try {
            return chatClient.prompt()
                    .user(prompt)
                    .call()
                    .content();
        } catch (Exception e) {
            // 如果AI调用失败，回退到原来的评语生成方式
            return "回答已提交，将在后续给出详细评语。";
        }
    }

    // 使用AI生成编程题评语
    private String generateProgrammingCommentByAI(Question question, String userAnswer) {
        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return "未提供答案，无法评分。";
        }

        String correctAnswer = (String) question.getAnswer();

        String prompt = String.format(
                "你是一个Java编程考试的阅卷老师。请根据以下信息生成评语：\n" +
                        "编程题目：%s\n" +
                        "参考答案：%s\n" +
                        "学生代码：%s\n" +
                        "请结合题目要求、参考答案和学生代码，给出200字左右的详细评语，包括代码质量、逻辑正确性和改进建议。",
                question.getQuestion(), correctAnswer, userAnswer
        );

        try {
            return chatClient.prompt()
                    .user(prompt)
                    .call()
                    .content();
        } catch (Exception e) {
            // 如果AI调用失败，回退到原来的评语生成方式
            return "代码已提交，将在后续给出详细评语。";
        }
    }
}
